#pragma once

#include <iostream>
#include <pthread.h>
#include <cstring>
#include <unistd.h>

namespace qds
{
    class task
    {
public:
        task()
        {
        }

        task(int sock)
            : _sock(sock)
        {
        }

        ~task()
        {
        }

        void service_IO()
        {
            // 提供服务,我们是一个死循环
            while (true)
            {
                char buffer[1024];
                bzero(buffer, strlen(buffer));

                ssize_t ret = read(_sock, buffer, sizeof(buffer) - 1);
                if (ret > 0)
                {
                    // 这里我们默认获取的内容是字符串
                    buffer[ret] = '\0';
                    std::cout << "client# " << buffer << std::endl;

                    std::string echo = "server# ";
                    echo += buffer;

                    write(_sock, echo.c_str(), echo.size());
                }
                else if (ret == 0)
                {
                    std::cout << "client quit !" << std::endl;
                    break;
                }
                else
                {
                    perror("read");
                    std::cerr << "errno : " << errno << std::endl;
                    break;
                }
            }
            close(_sock);
        }

        void operator()()
        {
            return service_IO();
        }

    private:
        int _sock;
    };
}
